package ework;

import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;

public class ColorDetector extends Frame {
    private static String color = "";
    private static Robot robot;
    private static int x;
    private static int y;

    static {
        try {
            robot = new Robot();
        } catch (AWTException e) {
            e.printStackTrace();
        }
    }

    public static void run() {
        ColorDetector cd = new ColorDetector();
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        cd.setSize(screenSize);
        cd.setUndecorated(true);
        cd.setOpacity(0.15f);
        cd.setVisible(true);

        cd.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
                    cd.dispose();
                }
            }
        });

        cd.addMouseMotionListener(new MouseAdapter() {
            @Override
            public void mouseMoved(MouseEvent e) {
                x = e.getX();
                y = e.getY();
                BufferedImage image = robot.createScreenCapture(new Rectangle(x, y, 1, 1));
                int rgb = image.getRGB(0, 0);
                Color col = new Color(rgb, true);
                int red = col.getRed();
                int green = col.getGreen();
                int blue = col.getBlue();
                color = String.format("#%02x%02x%02x", red, green, blue).toUpperCase();
                Graphics2D g = clear(cd);
                g.setColor(Color.RED);
                g.setStroke(new BasicStroke(2.0f));
                Font font = new Font(null, Font.BOLD, 16);
                g.setFont(font);
                g.drawString(color, x + 25, y + 25);
            }
        });

        cd.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseReleased(MouseEvent e) {
                Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
                clipboard.setContents(new StringSelection(color), null);
                Graphics2D g = clear(cd);
                g.drawString("已复制至粘贴板", x + 25, y + 25);
                try {
                    Thread.sleep(1500);
                } catch (InterruptedException interruptedException) {
                    interruptedException.printStackTrace();
                }
                cd.dispose();
            }
        });
    }

    public static Graphics2D clear(Frame frame) {
        Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
        Graphics2D g = (Graphics2D) frame.getGraphics();
        g.clearRect(0, 0, (int) dimension.getWidth(), (int) dimension.getHeight());
        return g;
    }
}
